﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.DepartmentTree;
using B.S.BasicData.Api.Read.DTOs;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.Api.Read.Application.Handler.DepartmentTree
{
    /// <summary>
    /// 部门树查询处理类
    /// </summary>
    public class GetDepartmentTreeHandler : IRequestHandler<GetDepartmentTreeCommand, ApiResult<List<DepartmentTreeDTO>>>
    {
        private readonly IBaseRepository<DepartmentModel> departmentRepo;
        private readonly IMapper mapper;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="departmentRepo">部门仓储</param>
        /// <param name="mapper">mapper组件</param>
        public GetDepartmentTreeHandler(IBaseRepository<DepartmentModel> departmentRepo,IMapper mapper)
        {
            this.departmentRepo = departmentRepo;
            this.mapper = mapper;
        }
        public async Task<ApiResult<List<DepartmentTreeDTO>>> Handle(GetDepartmentTreeCommand request, CancellationToken cancellationToken)
        {
            var res =new ApiResult<List<DepartmentTreeDTO>>();//实例化响应包装类
            res.Code = ApiEnum.Success;
            res.Msg = "查询部门树数据成功!";
            res.Data = GetTreeByParentId(0L);//递归查询
            return  res;
        }

        /// <summary>
        /// 根据父级id查找所有子数据
        /// </summary>
        /// <param name="parentId">父级编号:Long</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private List<DepartmentTreeDTO> GetTreeByParentId(long parentId)
        {
            //根据传入的父级id查找所有部门
            var departs = departmentRepo.GetAll().Where(x=>x.ParentId== parentId).ToList();
            //把查到的[部门实体列表]转成[DTO列表]
            var dtos  = mapper.Map<List<DepartmentTreeDTO>>(departs);
            //循环每一个部门dto,给dto的children赋值
            foreach (var d in dtos) {
                d.Children = GetTreeByParentId(d.Id);//递归查询
            }
            return dtos;
        }
    }
}
